package problem289;

//289.生命游戏
//https://leetcode.cn/problems/game-of-life/?envType=study-plan-v2&envId=top-interview-150

class Solution {
    public void gameOfLife(int[][] board) {
        int n = board.length, m = board[0].length;

        int[] xx = { 0, 0, 1, -1, -1, -1, 1, 1 };
        int[] yy = { -1, 1, 0, 0, -1, 1, -1, 1 };
        // 2:由死细胞复活的状态 0->2
        // 3:由活细胞死亡的状态 1->3
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {

                // 统计0, 1个数
                int cnt0 = 0, cnt1 = 0;
                for (int k = 0; k < 8; k++) {
                    int dx = i + xx[k];
                    int dy = j + yy[k];

                    if (dx >= 0 && dx < n && dy >= 0 && dy < m) {
                        if (board[dx][dy] == 0 || board[dx][dy] == 2)
                            cnt0++;
                        else if (board[dx][dy] == 1 || board[dx][dy] == 3)
                            cnt1++;
                    }
                }

                if (board[i][j] == 0) {
                    if (cnt1 == 3)
                        board[i][j] = 2;
                } else {
                    if (cnt1 < 2)
                        board[i][j] = 3;
                    if (cnt1 == 2 || cnt1 == 3)
                        board[i][j] = 1;
                    if (cnt1 > 3)
                        board[i][j] = 3;
                }
            }

        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == 2)
                    board[i][j] = 1;
                if (board[i][j] == 3)
                    board[i][j] = 0;
            }
        }
    }
}